<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\OperationTask as OperationTaskModel;
use app\admin\model\DistributeTaskLog;
use app\admin\model\Shop;
use app\admin\model\Admin;
use app\admin\model\User;
use think\Db;
use think\Session;
use think\Exception;

/**
 * 后台给兼职发放任务
 *
 * @icon   fa fa-list
 */
class OperationTask extends Backend
{

    protected $model = null;
    protected $group_id = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OperationTaskModel();
        $admin = Session::get('admin');
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        $this->group_id = $group_id;
        $this->admin = $admin;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');

            if($this->group_id == 7){
                $where1 = ['admin_id'=>$this->admin['id']];
            }else{
                $where1 = [];
            }


            $list = $this->model
                ->where($where1)
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['admin_name'] = Admin::where(['id'=>$v['admin_id']])->value('nickname');
                $v['imgs'] = str_replace('www.sulamarketing.com', 'oa.yuxiang123.cn', $v['imgs'] );
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
   /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            if($this->group_id == 7){
                $type_arr = Shop::where(['status'=>1,'id'=>['in',$this->admin['shop_ids']]])->column('name');
            }else{
                $type_arr = Shop::where(['status'=>1])->column('name');
            }
            $this->view->assign('type_arr', $type_arr);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if(!$params['title']){
            $this->error('标题不可为空');
        }
        if(!$params['imgs']){
            $this->error('图片不可为空');
        }
        $result = false;
        $admin = $this->admin;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['add_time'] = time();
            $params['price'] = 3;
            //通过提交的数据进行判断金额
            $count = count(explode(',',$params['imgs']));
            if($count > 1){
                $params['price'] += 2;
            }
            if($params['content']){
                $params['price'] += 3;
            }
            $params['admin_id'] = $admin['id'];
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            if($this->group_id == 7){
                $type_arr = Shop::where(['status'=>1,'id'=>['in',$this->admin['shop_ids']]])->column('name');
            }else{
                $type_arr = Shop::where(['status'=>1])->column('name');
            }
            $this->view->assign('type_arr', $type_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    //完成或拒绝
    public function complete_operation_task()
    {
        $admin = $this->admin;;
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        if($group_id != 1){
            $this->error('无操作权限');
        }
        $result = $this->request->request();
        $info = $this->model->where(['id'=>$result['ids'],'status'=>0])->find();
        if($info){
            $this->model->where(['id'=>$info['id']])->update(['status'=>$result['status']]);
            $user_id = Admin::where(['id'=>$info['admin_id']])->value('user_id');
            if($user_id && $result['status'] == 1){
                $userInfo = User::where(['id'=>$user_id])->find();
                //给用户账户余额加钱
                User::where(['id'=>$user_id])->update(['task_price'=>$userInfo['task_price'] + $info['price']]);
                //记录佣金日志
                $arr = [
                    'user_id'=>$user_id,
                    'new_price'=>$userInfo['task_price'],
                    'price'=>$info['price'],
                    'old_price'=>$userInfo['task_price']+$info['price'],
                    'add_time'=>time()
                ];
                DistributeTaskLog::insert($arr);
            }
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }


        
        
    }


}